﻿@using System.ComponentModel.DataAnnotations
@using Blazor.Localization
@inherits Blazor.Core.SoraniFeedbackComponentBase<DeviceEntryEditorOption, DeviceEntryEditorResult?>
@inject IStringLocalizer<DeviceListLocalization> Loc;

<Form @ref="_form" Model="_model" LabelColSpan="8" WrapperColSpan="16" LabelAlign="AntLabelAlignType.Left">
    <FormItem Label="@Loc[DeviceListLocalization.Id]">
        <Input @bind-value="@context.Id"
               Disabled="@((Options.Type & DeviceEntryEditorOption.EditType.Name) == 0)"/>
    </FormItem>

    <FormItem Label="@Loc[DeviceListLocalization.Description]">
        <Input @bind-value="@context.Description"
               Disabled="@((Options.Type & DeviceEntryEditorOption.EditType.Id) == 0)"/>
    </FormItem>
</Form>

@code {
    private class FormData
    {
        [Length(10, 50, ErrorMessageResourceName = nameof(DeviceListLocalization.DeviceIdlengthTip), ErrorMessageResourceType = typeof(DeviceListLocalization))]
        public string Id { get; set; }

        [Length(1, 30, ErrorMessageResourceName = nameof(DeviceListLocalization.DeviceNameLengthTip), ErrorMessageResourceType = typeof(DeviceListLocalization))]
        public string Description { get; set; }
    }

    private FormData _model;
    private Form<FormData> _form;

    protected override void OnInitialized()
    {
        _model = new FormData()
        {
            Id = Options.Id ?? string.Empty,
            Description = Options.Description ?? string.Empty,
        };

        base.OnInitialized();
    }

    public override Task OnFeedbackOkAsync(ModalClosingEventArgs args)
    {
        if (!_form.Validate())
        {
            args.Reject();
            return Task.CompletedTask;
        }

        var result = new DeviceEntryEditorResult(_model.Id, _model.Description);
        OkCancelRefWithResult.OkAsync(result);

        return Task.CompletedTask;
    }

}